package org.jeecgframework.web.service.impl;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.system.pojo.base.CbsContractEntity;
import org.jeecgframework.web.service.CbsContractServiceI;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.io.Serializable;

@Service("cbsContractService")
@Transactional
public class CbsContractServiceImpl extends CommonServiceImpl implements CbsContractServiceI {

	@Autowired
	private SystemService systemService;

 	public <T> void delete(T entity) {
 		super.delete(entity);
 		//执行删除操作配置的sql增强
		this.doDelSql((CbsContractEntity)entity);
 	}
 	
 	public <T> Serializable save(T entity) {
 		Serializable t = super.save(entity);
 		//执行新增操作配置的sql增强
 		this.doAddSql((CbsContractEntity)entity);
 		return t;
 	}
 	
 	public <T> void saveOrUpdate(T entity) {
 		super.saveOrUpdate(entity);
 		//执行更新操作配置的sql增强
 		this.doUpdateSql((CbsContractEntity)entity);
 	}
 	
 	/**
	 * 默认按钮-sql增强-新增操作
	 * @param id
	 * @return
	 */
 	public boolean doAddSql(CbsContractEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-更新操作
	 * @param id
	 * @return
	 */
 	public boolean doUpdateSql(CbsContractEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-删除操作
	 * @param id
	 * @return
	 */
 	public boolean doDelSql(CbsContractEntity t){
	 	return true;
 	}

 	/*导出*/
	@Override
	public void exportXls(HttpServletRequest request, HttpServletResponse response) {
		OutputStream out = null;
		try {
			String fileName = "合同管理.xlsx";
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename=" + (new String(fileName.getBytes("gb2312"), "ISO8859-1")));
			out = response.getOutputStream();
			String[] planIdsArr = oConvertUtils.getString(request.getParameter("planIds")).split(",");
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT\n" +
					"IFNULL(c.id,'') AS id,\n" +
					"IFNULL(mc.sn,'') AS sn,\n" +
					"IFNULL(mc.equipment_type,'') as equipmentType,\n" +
					"IFNULL(c.client_Name,'') as clientName,\n" +
					"IFNULL(mc.cinema_Name,'') as cinemaName,\n" +
					"IFNULL(mc.contract_code,'') as contractCode,\n" +
					"CASE c.contract_type\n" +
					"WHEN '"+ StaticValue.CBS_CONTRACT_TYPE_WB+"' THEN\n" +
					"\t'维保合同'\n" +
					"WHEN '"+ StaticValue.CBS_CONTRACT_TYPE_SS+"' THEN\n" +
					"\t'销售合同'\n" +
					"WHEN '"+ StaticValue.CBS_CONTRACT_TYPE_MB+"' THEN\n" +
					"\t'模板合同'\n" +
					"WHEN '"+ StaticValue.CBS_CONTRACT_TYPE_QT+"' THEN\n" +
					"\t'其他'\n" +
					"ELSE\n" +
					"\t''\n" +
					"END AS contractType,\n" +
					"IFNULL(mc.service_Start_Date,'') as serviceStartDate,\n" +
					"IFNULL(mc.service_End_Date,'') as serviceEndDate,\n" +
					" CASE mc.`status`\n" +
					"WHEN '"+StaticValue.mc_status_1+"' THEN\n" +
					"\t'未生效'\n" +
					"WHEN '"+StaticValue.mc_status_2+"' THEN\n" +
					"\t'生效中'\n" +
                    "WHEN '"+StaticValue.mc_status_3+"' THEN\n" +
                    "\t'已取消'\n" +
                    "WHEN '"+StaticValue.mc_status_4+"' THEN\n" +
                    "\t'已失效'\n" +
					"ELSE\n" +
					"\t''\n" +
					"END AS STATUS,\n" +
					"CASE c.pay_Status\n" +
					"WHEN '"+StaticValue.CBS_CONTRACT_payStatus_1+"' THEN\n" +
					"\t'未付款'\n" +
					"WHEN '"+StaticValue.CBS_CONTRACT_payStatus_2+"' THEN\n" +
					"\t'已付款'\n" +
					"ELSE\n" +
					"\t''\n" +
					"END AS payStatus,\n" +
					"IFNULL(c.contract_Date,'') as contractDate,\n" +
					"IFNULL(mc.mc_code,'') as mcCode \n" +
					"FROM\n" +
					"cbs_contract c \n" +
					"LEFT JOIN cbs_contract_mc_equipment mc ON mc.contract_code = c.contract_code\n" +
					"WHERE\n" +
					"c.contract_code IS NOT NULL");
			sql.append(" and ");
			sql.append(" c.id IN ( ");
			for (int i = 0; i < planIdsArr.length; i++) {
				if (i == planIdsArr.length - 1) {
					sql.append("'" + planIdsArr[i] + "'");
				} else {
					sql.append("'" + planIdsArr[i] + "',");
				}
			}
			sql.append(" 	) ORDER BY c.create_date DESC");
			List<Map<String, Object>> reusltMaps = super.findForJdbc(sql.toString());
			TSUser user = ResourceUtil.getSessionUserName();
			systemService.addLog(user.getRealName()+"导出"+reusltMaps.size()+"条合同管理记录", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

			InputStream is = ZyInspectionPlanServiceImpl.class.getClassLoader().getResourceAsStream("jeecg/template/cbsContractList.xlsx");
			XSSFWorkbook xssf = new XSSFWorkbook(is);
			XSSFSheet sheet = xssf.getSheetAt(0);
			int rowNum = 1;
			for (Map<String, Object> dataMap : reusltMaps) {
				XSSFRow row = sheet.createRow(rowNum);
				int cellNum = 0, index = 0;
				for (String key : dataMap.keySet()) {
					if (index == 0) {
						index++;
						continue;
					}
					XSSFCell cell = row.createCell(cellNum);
					cell.setCellValue(dataMap.get(key) != null ? dataMap.get(key).toString() : "");
					cellNum++;
				}
				rowNum++;
			}
			xssf.write(out);
		}catch (IOException e){
			e.printStackTrace();
		}finally {
			try {
				if (out != null) {
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 替换sql中的变量
	 * @param sql
	 * @return
	 */
 	public String replaceVal(String sql,CbsContractEntity t){
 		sql  = sql.replace("#{id}",String.valueOf(t.getId()));
 		sql  = sql.replace("#{contract_code}",String.valueOf(t.getContractCode()));
 		sql  = sql.replace("#{contract_name}",String.valueOf(t.getContractName()));
 		sql  = sql.replace("#{contract_type}",String.valueOf(t.getContractType()));
 		sql  = sql.replace("#{client_name}",String.valueOf(t.getClientName()));
 		sql  = sql.replace("#{contract_date}",String.valueOf(t.getContractDate()));
 		sql  = sql.replace("#{contract_sign_user}",String.valueOf(t.getContractSignUser()));
 		sql  = sql.replace("#{memo}",String.valueOf(t.getMemo()));
 		sql  = sql.replace("#{repair_provider}",String.valueOf(t.getRepairProvider()));
 		sql  = sql.replace("#{repair_type}",String.valueOf(t.getRepairType()));
 		sql  = sql.replace("#{inspection_provider}",String.valueOf(t.getInspectionProvider()));
 		sql  = sql.replace("#{inspection_type}",String.valueOf(t.getInspectionType()));
 		sql  = sql.replace("#{service_commitment}",String.valueOf(t.getServiceCommitment()));
 		sql  = sql.replace("#{pay_status}",String.valueOf(t.getPayStatus()));
 		sql  = sql.replace("#{pay_date}",String.valueOf(t.getPayDate()));
 		sql  = sql.replace("#{status}",String.valueOf(t.getStatus()));
 		sql  = sql.replace("#{create_name}",String.valueOf(t.getCreateName()));
 		sql  = sql.replace("#{create_by}",String.valueOf(t.getCreateBy()));
 		sql  = sql.replace("#{create_date}",String.valueOf(t.getCreateDate()));
 		sql  = sql.replace("#{update_name}",String.valueOf(t.getUpdateName()));
 		sql  = sql.replace("#{update_by}",String.valueOf(t.getUpdateBy()));
 		sql  = sql.replace("#{update_date}",String.valueOf(t.getUpdateDate()));
 		sql  = sql.replace("#{UUID}",UUID.randomUUID().toString());
 		return sql;
 	}
}